package org.thinkinbunny.financial.login;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.thinkinbunny.financial.R;
import org.thinkinbunny.financial.activity.MyActivity;
import org.thinkinbunny.financial.activity.SyncActivity;
import org.thinkinbunny.financial.billentity.UserEntiry;
import org.thinkinbunny.financial.encrypt.Encrypt;
import org.thinkinbunny.financial.http.HttpTools;
import org.thinkinbunny.financial.util.Constant;
import org.thinkinbunny.financial.util.DLog;
import org.thinkinbunny.financial.util.ShowTools;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class LoginActivity extends MyActivity implements
		android.view.View.OnClickListener {
	Button loginButton, register_button;
	EditText login_input_name, login_input_password;
	boolean remembeUser = false;
	boolean savedUser = false;
	CheckBox remember_user;
	SharedPreferences pref;// = getSharedPreferences (Constant.FILE_SHARE,
	// Context.MODE_PRIVATE);
	private ProgressDialog mpDialog;
	Button btnUpdate, btnCancel;
	Encrypt encrypt = new Encrypt();
	UserEntiry userEntiry = new UserEntiry();
	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case 0:
				mpDialog.show();
				break;
			case 1:
				mpDialog.dismiss();
				break;

			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_login);
		userEntiry = null;
		try {
			Bundle bundle = getIntent().getBundleExtra("userEntiryBundle");

			userEntiry = (UserEntiry) bundle.getSerializable("userEntiry");
		} catch (Exception e) {
			// TODO: handle exception
			// e.printStackTrace();
		}
		init_UI();
		super.onCreate(savedInstanceState);

	}

	void init_UI() {
		mpDialog = new ProgressDialog(LoginActivity.this);
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
		mpDialog.setTitle(getString(R.string.logining));// 设置标题
		// mpDialog.setIcon(R.drawable.ic_launcher);// 设置图标
		mpDialog.setMessage(getString(R.string.checkuser));
		mpDialog.setIndeterminate(false);// 设置进度条是否为不明确

		mpDialog.setCancelable(false);// 设置进度条是否可以按退回键取消
		pref = getSharedPreferences(Constant.FILE_SHARE, Context.MODE_PRIVATE);
		loginButton = (Button) findViewById(R.id.login_comfirm_button);
		register_button = (Button) findViewById(R.id.register_button);
		register_button.setOnClickListener(this);
		login_input_name = (EditText) findViewById(R.id.login_input_name);
		login_input_password = (EditText) findViewById(R.id.login_input_password);
		remember_user = (CheckBox) findViewById(R.id.remember_user);
		loginButton.setOnClickListener(this);
		readUser(true);

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (userEntiry != null) {
			login_input_name.setText(userEntiry.getUsername());
			login_input_password.setText(userEntiry.getPassword());
		}
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.login_comfirm_button: {
			if (checkUser()) {
				Message msgMessage = mHandler.obtainMessage(0);
				mHandler.sendMessage(msgMessage);
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						DoLogin();
						super.run();
					}
				}.start();
			}

		}

			// userManger(true);

			break;
		case R.id.register_button:
			startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
			finish();
			break;

		default:
			break;
		}

	}

	boolean checkUser() {
		if (login_input_name.getText().toString().trim().length() < 6) {
			login_input_name.setError(getString(R.string.login_userErr));
			return false;
		}
		if (login_input_password.getText().toString().trim().length() < 6) {
			login_input_password.setError(getString(R.string.login_pwdErr));
			return false;
		}
		return true;
	}

	private void DoLogin() {
		if (userEntiry == null) {
			userEntiry = new UserEntiry();

		}
		userEntiry.setUsername(login_input_name.getText().toString().trim());
		if (pref.getBoolean("saved", false)) {
			userEntiry.setPassword(login_input_password.getText().toString()
					.trim());
		}else {
			userEntiry.setPassword(EncryptPasswordWithSHA1(login_input_password
					.getText().toString().trim()));
		}
	 if (!pref.getString("username", "").equals(login_input_name.getText().toString().trim())) {
			userEntiry.setPassword(EncryptPasswordWithSHA1(login_input_password
					.getText().toString().trim()));
			}

		userEntiry.setRemember(remember_user.isChecked());

		UserEntiry temp = HttpTools.HttpGetDataCheckUser("login", userEntiry);
		if (temp == null) {
			ShowTools.toastInThread(getString(R.string.login_error));
			DLog.i("LoginActivity", "login error"+userEntiry.toString());
		} else {
			// if (!readUser(false)) {

			saveUser(userEntiry);
			Intent intent = new Intent(LoginActivity.this, SyncActivity.class);
			Bundle bundle = new Bundle();

			bundle.putSerializable("userEntiry", userEntiry);
			intent.putExtra("userEntiryBundle", bundle);
			startActivity(intent);
			// startActivity(new Intent(getApplicationContext(),
			// SyncActivity.class));
			finish();
			// }
		}
		Message msgMessage = mHandler.obtainMessage(1);
		mHandler.sendMessage(msgMessage);
	}

	private String EncryptPasswordWithSHA1(String str) {

		return encrypt.getSHA(str);
	}

	private String EncryptPassword(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			// System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString().toUpperCase();
	}

	boolean readUser(boolean tryset) {
		if (pref.getBoolean("saved", false)) {
			if (tryset) {
				login_input_name.setText(pref.getString("username", ""));
				login_input_password.setText(pref.getString("password", ""));
				remember_user.setChecked(true);
			}

			return true;
		}
		return false;

	}

	void saveUser(UserEntiry userEntiry) {

		Editor ed = pref.edit();
		musername = login_input_name.getText().toString().trim();
		;
		if (userEntiry.isRemember()) {
			ed.clear();
			ed.putString("username", userEntiry.getUsername());

			ed.putString("password", userEntiry.getPassword());
			ed.putBoolean("saved", userEntiry.isRemember());
		}

		ed.commit();
		// DbHelper dbHelper=new DbHelper(getApplicationContext(),
		// DbHelper.DbName);
		// SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
		// dbHelper.createUserAccount(getApplicationContext(), musername);

	}
}
